//
//  URL+Extension.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/3.
//

import Foundation

extension URL: LXSExtensionCompatible {}

extension LXS where Base == URL {
    public static func encoding(string: String, ignoreEncodedCharacters: String? = "!*’();:@&=+$,/?%#[]") -> URL?
    {
        URL(string: string, ignoreEncodedCharacters: ignoreEncodedCharacters)
    }
}

extension URL {
    
    /// @param ignoreEncodedCharacters 除了url里面的#不进行encoding，其他该转码的都会被encoing, 比如防止url中的#被转码成了%23
    /// 需要忽略的编码：!*’();:@&=+$,/?%#[]
    public init?(string: String, ignoreEncodedCharacters: String?) {
        let encodingStr = string.lxs.encoding(ignoreCharacters: ignoreEncodedCharacters)
        self.init(string: encodingStr)
    }
}

extension LXS where Base : StringProtocol {
    /// 字符串进行url编码
    /// ignoreCharacters 忽略编码的字符 除了url里面的#不进行encoding，其他该转码的都会被encoing, 比如防止url中的#被转码成了%23
    /// addCharacters 增加需要编码的字符
    public func encoding(ignoreCharacters: String? = nil, addCharacters: String? = nil) -> String {
        let ignoreArr = ignoreCharacters?.components(separatedBy: "")
        var charSet = CharacterSet.urlQueryAllowed
        ignoreArr?.forEach({ (char) in
            charSet.insert(charactersIn: char)
        })
        
        let addArr = addCharacters?.components(separatedBy: "")
        addArr?.forEach({ (char) in
            charSet.remove(charactersIn: String(char))
        })
        
        let encodingStr = base.addingPercentEncoding(withAllowedCharacters: charSet )
        return encodingStr ?? ""
    }
}
